# coding:utf-8
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *


class Browser(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(500, 200, 1200, 800)
        self.InIt()
        # self.show()

    def InIt(self):
        layout = QVBoxLayout()  # 创建一个垂直布局管理器

        self.browser = QWebEngineView()
        self.browser.setUrl(QUrl("https://www.bilibili.com/"))

        layout.addWidget(self.browser)  # 将浏览器添加到布局中
        widget = QWidget()  # 创建一个 QWidget 对象
        widget.setLayout(layout)  # 设置 QWidget 的布局为我们刚刚创建的布局

        self.setCentralWidget(self.browser)
        self.browser.urlChanged.connect(self.update_urlbar)
        self.browser.loadFinished.connect(self.update_title)

        self.status = QStatusBar()
        self.setStatusBar(self.status)
        navtb = QToolBar("导航")
        self.addToolBar(navtb)
        back_btn = QAction("后退", self)
        back_btn.setStatusTip("返回上一页")
        back_btn.triggered.connect(self.browser.back)
        navtb.addAction(back_btn)
        next_btn = QAction("前进", self)
        next_btn.setStatusTip("前进到下一页")
        next_btn.triggered.connect(self.browser.forward)
        navtb.addAction(next_btn)
        reload_btn = QAction("刷新", self)
        reload_btn.setStatusTip("刷新页面")
        reload_btn.triggered.connect(self.browser.reload)
        navtb.addAction(reload_btn)
        home_btn = QAction("主页", self)
        home_btn.setStatusTip("返回主页")
        home_btn.triggered.connect(self.navigate_home)

        navtb.addAction(home_btn)
        navtb.addSeparator()
        navtb.addSeparator()
        navtb.addSeparator()
        self.urlbar = QLineEdit()
        self.urlbar.returnPressed.connect(self.navigate_to_url)
        navtb.addWidget(self.urlbar)

        stop_btn = QAction("停止", self)
        stop_btn.setStatusTip("停止加载当前页面")
        stop_btn.triggered.connect(self.browser.stop)
        navtb.addAction(stop_btn)

        source_btn = QAction("查看源码", self)  # 添加查看源码按钮
        source_btn.setStatusTip("查看网页源码")
        source_btn.triggered.connect(self.view_source)
        navtb.addAction(source_btn)
        self.navtb = navtb

        # 在Browser类的__init__方法中添加以下代码
        self.web_engine_profile = QWebEngineProfile.defaultProfile()
        self.web_engine_cookie_store = self.web_engine_profile.cookieStore()
        self.web_engine_cookie_store.cookieAdded.connect(self.get_cookies)

        # 存储cookies
        self.cookies = {}

    def get_cookies(self, cookie):
        # 'cookie': '; '.join([f'{name}={value}' for name, value in cookies.items()]), 写入headers即可
        # 处理会话Cookie，您可以将其存储下来以备后续使用
        cookie_name = cookie.name().data().decode()
        cookie_value = cookie.value().data().decode()
        # 存储Cookie，以备后续请求使用
        # 您可以使用requests库或其他HTTP库来发送包含这些Cookie的请求
        self.cookies[cookie_name] = cookie_value

    def update_title(self):
        title = self.browser.page().title()
        self.setWindowTitle(f"{title} - 登录")

    def navigate_home(self):
        self.browser.setUrl(QUrl("https://www.baidu.com"))

    def navigate_to_url(self):
        q = QUrl(self.urlbar.text())
        if q.scheme() == "":
            q.setScheme("http")

        self.browser.setUrl(q)
        print("点击了链接...", QUrl(self.urlbar.text()))

    def update_urlbar(self, q):
        if q.scheme() == 'https':
            self.urlbar.setStyleSheet("color: green")
        else:
            self.urlbar.setStyleSheet("color: black")
        self.urlbar.setText(q.toString())
        self.urlbar.setCursorPosition(0)

    def view_source(self):
        # 获取网页源码
        self.browser.page().toHtml(self.get_source)

    def get_source(self, source):
        # 创建对话框以显示网页源码
        dialog = QDialog(self)
        dialog.setWindowTitle('网页源码')
        dialog.setGeometry(100, 100, 800, 600)
        layout = QVBoxLayout()
        text_edit = QTextEdit(dialog)
        text_edit.setPlainText(source)
        layout.addWidget(text_edit)
        dialog.setLayout(layout)
        dialog.exec_()
